/*
    vega
    Copyright (c) Vlad Dimitriu

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <getopt.h>

#include <self.h>

static const char *log_label[] = { "INFO", "WARN", "ERROR", "DEBUG" };

struct self s = {
	.path = ".",
	.log.name = "vega.log",
	.log.level = INFO,
	.log.file = NULL,
	.ip = "127.0.0.1",
	.port = "80"
};


void v_log(enum log_level level, char const *form, ...)
{

	va_list arguments;

	if (s.log.level <= level) return;
	va_start(arguments, form);

	fprintf(s.log.file ? s.log.file : stderr,"%s ", log_label[s.log.level]);
	vfprintf(s.log.file ? s.log.file : stderr, form, arguments);
	fprintf(s.log.file ? s.log.file : stderr,"\n");

	va_end(arguments);

}

void *report_self_configuration(void) {
	sprintf(s.buffer, "self:\n"
		"path      %s\n"
		"log_file  %s\n"
		"log_level %s\n"
		"ip        %s\n"
		"port      %s\n",
		s.path,	s.log.name, log_label[s.log.level], s.ip, s.port);
}

void init_self(int argc, char **argv)
{
	int c;

	while (1) {
		static struct option long_options[] = {
			{"directory", optional_argument, 0, 'd'},
			{"log-level", optional_argument, 0, 'l'},
			{"log-file",  optional_argument, 0, 'f'},
			{"ip",        optional_argument, 0, 'i'},
			{"port",      optional_argument, 0, 'p'},
			{0, 0, 0, 0}
		};

		int option_index = 0;

		c = getopt_long(argc, argv, "d:l:f:i:p:",
				long_options, &option_index);

		if (c == -1) break;

		switch (c) {
		case 0:
			break;
		case 'd':
			s.path = optarg;
			break;
		case 'l':
			if (!strcmp(optarg, "INFO")) {
				s.log.level = INFO;
				break;
			}
			if (!strcmp(optarg, "WARN")) {
				s.log.level = WARN;
				break;
			}
			if (!strcmp(optarg, "ERROR")) {
				s.log.level = ERROR;
				break;
			}
			if (!strcmp(optarg, "DEBUG")) {
				s.log.level = DEBUG;
				break;
			}
		case 'f':
			s.log.name = optarg;
			break;
		case 'i':
			s.ip = optarg;
			break;
		case 'p':
			s.port = optarg;
			break;
		default:
			abort();
		}
	}

	v_log(DEBUG, (report_self_configuration(), s.buffer));
}
